package com.wantup.demo03xd.part05.communication.demo6;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author Zhaoluowei
 * @version 1.0
 * @date 2019/7/3 15:27
 */
public class Medium {

    private int num = 0;
    //是库存
    private static final int TOTAL = 20;

    //设置锁
    private Lock lock = new ReentrantLock();
    private Condition consumerCondition = lock.newCondition();
    private Condition productCondition = lock.newCondition();


    public void put() {
        lock.lock();
        try {
            if (num < TOTAL) {
                //继续生产
                System.out.println("新增库存 ---- 当前库存 " + ++num);

                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                consumerCondition.signalAll();
            } else {
                //库存满了 通知生产者进行等待
                try {
                    System.out.println("新增库存 ---- 库存已满 " + num);
                    productCondition.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

        } finally {
            lock.unlock();
        }


    }

    public void take() {
        lock.lock();
        try {

            if (num > 0) {
                //消费
                System.out.println("消费库存 ---- 当前库存 " + --num);

                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                productCondition.signalAll();
            } else {
                //等待
                try {
                    System.out.println("消费库存 ---- 当前库存不足 " + num);
                    consumerCondition.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

        } finally {
            lock.unlock();
        }


    }


}
